package com.wsh.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsh.entity.sys.FileEntity;
import com.wsh.mapper.sys.FileDao;
import com.wsh.utils.FileUtil;
import com.wsh.utils.StringUtils;
import com.wsh.vo.sys.FileVo;
import com.wsh.sys.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author 王思涵
 * @Date 2019/8/3
 * @Version 1.0
 * @Desciption 文件管理业务接口实现类
 **/
@Service
public class FileServiceImpl extends ServiceImpl<FileDao, FileEntity> implements FileService {

    @Value("${filePath}")
    private String disPath;

    @Override
    public Map<String, Object> saveFileInfo(FileVo fileVo) throws Exception {
        MultipartFile file = fileVo.getFile();

        // 处理真实文件名
        String fileName = file.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = UUID.randomUUID() + ext;

        // 上传路径处理
        String diskPath = ResourceUtils.getFile(fileVo.getDiskPath()).getPath() + File.separator + fileVo.getFilePath() + File.separator;
        File uploadPath = new File(diskPath);
        if (!uploadPath.exists()) {
            uploadPath.mkdirs();
        }
        file.transferTo(new File(diskPath + newFileName));

        // 实体类规范
        FileEntity fileEntity = new FileEntity();
        fileEntity.setRealName(fileName);
        fileEntity.setDiskPath(diskPath);
        fileEntity.setEditType(fileVo.getEditorType());
        fileEntity.setFileName(fileVo.getFilePath() + File.separator + newFileName);
        fileEntity.setFileType(fileVo.getFileType());
        fileEntity.setUploadTime(new Date());
        fileEntity.setProcessId(fileVo.getProcessId());

        // 数据入库
        save(fileEntity);

        Map<String, Object> maps = new HashMap<>();
        maps.put("fileId", fileEntity.getFileId());
        maps.put("fileName", newFileName);

        return maps;
    }

    @Override
    public boolean uploadFormId(List<FileEntity> fileList, String[] removeIds, String formId) {

        // 删除附件
        if (removeIds != null && removeIds.length > 0) {
            removeByIds(Arrays.asList(removeIds));
        }

        // 更新formId
        if (fileList != null && fileList.size() > 0) {
            List<String> collect = fileList.stream().map(FileEntity::getFileId).collect(Collectors.toList());
            List<FileEntity> fileEntities = (List<FileEntity>) listByIds(collect);
            for (FileEntity fileEntity : fileEntities) {
                fileEntity.setFormId(formId);
            }
            return updateBatchById(fileEntities);
        }
        return true;
    }

    public List<FileEntity> findFileListByFormId(String formId) {
        return baseMapper.findFileListByFormId(formId);
    }

    @Override
    public List<Map<String, Object>> getListByFormId(String formId, Boolean toBase64) {
        QueryWrapper<FileEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(new FileEntity());
        queryWrapper.select("file_id as fileId", "real_name as name", "file_name as url", "process_id as processId");
        queryWrapper.eq("form_id", formId);
        List<Map<String, Object>> fileList = baseMapper.selectMaps(queryWrapper);

        // base64处理
        if (toBase64 && fileList.size() > 0) {
            for (Map<String, Object> fileInfo : fileList) {
                String url = (String) fileInfo.get("url");
                if (StringUtils.isNotBlank(url)) {
                    fileInfo.put("base64", FileUtil.fileToBase64(new File(this.disPath + File.separator + url)));
                }
            }
        }
        return fileList;
    }

    @Override
    public String getFileBase64(String url) {
        return FileUtil.fileToBase64(new File(this.disPath + File.separator + url));
    }
}
